<!-- 蓝牙和位置都需要打开-->
<template>
	<view class="content">
		<view >设备列表</view>
		  <text>{{msg}}</text>
		  <view class="section section_gap">
		    <text class="section__title">RSSI过滤设置</text>
		    <view class="body-view">
		        <slider name="RSSI" @change="sliderRSSIchange" max='-20' min='-100' :value="RSSIValue" show-value/>
		    </view>
		    <!-- <text class="section__title">名字过滤设置</text> -->
		    <view class="inputView">
		    <input class="input" name="BTName" :value="BTNameValue" placeholder="请输入蓝牙名字" auto-focus  maxlength="32"  @input="BTNameInput"/>
		    </view>
		  </view>
		
		<view class="devices_summary">已发现 {{mydevices.length}} 个外围设备：</view>
		<scroll-view class="device_list" scroll-y scroll-with-animation upper-threshold='50' scroll-top='50' scroll-left="10">
		  <view v-for="(item,index) in mydevices" :key="index"
		   :data-device-id="item.deviceId"
		   :data-name="item.name || item.localName"
		   class="device_item"
		   hover-class="device_item_hover" 
		   :data-title="item.deviceId"  
		   :data-advertisData="item.advertisServiceUUIDs"    @tap="bindViewTap">
		    <view style="font-size: 16px; color: #333;">设备名称:{{item.name}}</view>
		    <!-- <view style="font-size: 10px">信号强度: {{item.RSSI}}dBm ({{util.max(0, item.RSSI + 100)}}%)</view> -->
		    <view style="font-size: 10px">DeviceID: {{item.deviceId}}</view>    
		    <view style="font-size: 10px">AdvMAC: {{item.advMac}}</view>         
		  </view>
		</scroll-view>
		
	</view>
</template>

<script>

import * as zksdk from '../../utils/bluetoolth';
var util = require('../../utils/util.js');
const errMsg = {
    10000: '未初始化蓝牙模块',
    10001: '蓝牙未打开',
    10002: '没有找到指定设备',
    10003: '连接失败',
    10004: '没有找到指定服务',
    10005: '没有找到指定特征值',
    10006: '当前连接已断开',
    10007: '当前特征值不支持此操作',
    10008: '系统上报异常',
    10009: '系统版本低于 4.3 不支持BLE'
};
function debounce(func, wait) {
    let timer = null;
    return function(opt) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            func && func.call(this, opt);
        }, wait || 60);
    };
}

	export default {
		components: {},
		data() {
			return {
				logs: [],
				list:[],  
				mydevices: [],  
				deviceName: '',
				deviceId: '',
				advdata:[],
				msg:'',
				rssi:'-100',
				BTName:'',
				BTNameValue:'',
				selIds:'',
				prtQtys:'',
			}
		},
		onShow:function(){
		  console.log("OnShow");
		  //搜寻设备
		  zksdk.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, interval: 500 });
		  //监听寻找新设备
		  zksdk.onfindBlueDevices(this.onGetDevice)
		},
		
		onUnload:function(){
		  //----关闭扫描蓝牙设备----
		  zksdk.stopBlueDevicesDiscovery();
		},
		onLoad(p) {
			const data = JSON.parse(p.data)
			this.selIds = data.selIds
			this.prtQtys = data.prtQtys
			
			
            var that = this;
            console.log('bluetooththr onLoad')
            var rssi = wx.getStorageSync('RSSI');
            var BTName = wx.getStorageSync('BTName');
            
            that.BTNameValue= BTName;
			that.RSSIValue= '-100';
            if(rssi==undefined)   that.RSSIValue= '-100';
            else  that.RSSIValue= rssi;
            that.BTName=BTName;
            that.rssi=rssi;
            zksdk.openBlue()
              .then((res) => {
                //搜寻设备
                zksdk.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, interval: 500 });
                //监听寻找新设备
                zksdk.onfindBlueDevices(this.onGetDevice)})
              .catch((res) => {
                console.log('catch res:'+res);
                const coode = res.errCode ? res.errCode.toString() : '';
                const msg = errMsg[coode];
                wx.showToast({
                  title: msg || coode,
                  icon: 'none',
                });
              });
            
		},
		methods: {
			BTNameInput(e) {
			  var that = this;
			  that.BTNameValue=e.detail.value;
			  that.BTName = e.detail.value;
			  wx.setStorageSync('BTName', e.detail.value);
			  console.log('that.BTName:', that.BTName);
			},
			compare(property) {
			  return function (a, b) {    
			    var nameA = a.name.toUpperCase(); // ignore upper and lowercase
			    var nameB = b.name.toUpperCase(); // ignore upper and lowercase
			    if (nameA < nameB) {
			      return -1;
			    }
			    if (nameA > nameB) {
			      return 1;
			    }    
			    return 0;
			  }
			},

			getNewDevicesList(devices, name) {
			  var that = this;
			  var newDevices = devices;
			  var rssi = that.rssi;
			  console.log('RSSI:', rssi);
			
			  //按RSSI过滤
			  for (var i = 0; i < newDevices.length;) {
			    if (newDevices[i].RSSI < rssi) newDevices.splice(i, 1);
			    else i++;
			  }
			
			  // 按名字过滤
			  if (name != '') {
			    for (var i = 0; i < newDevices.length;) {
			      if (newDevices[i].name.indexOf(name) == 0) i++;
			      else newDevices.splice(i, 1);
			    }
			  }
			  console.log("Get Mac");
			  // 广播数据提取MAC地址
			  for (var i = 0; i < newDevices.length; i++) {
			    if (newDevices[i].hasOwnProperty('advertisData')) {
			      console.log(newDevices[i].advertisData);
			      console.log(newDevices[i].advertisData.byteLength);
			      if (newDevices[i].advertisData.byteLength == 8) {
			        //newDevices[i].add("adv");
			        console.log("Adv MAC Address");
			        console.log(util.buf2hex(newDevices[i].advertisData));
			        newDevices[i].advMac = util.buf2hex(newDevices[i].advertisData.slice(2, 7));
			      }
			    }
			  }
			
			  newDevices.sort(this.compare("name"));
			  return newDevices;
			},

			onGetDevice:function(res){
			  var that = this;   
			  var dev; 
			    console.log('onGetDevice', res); 
			    console.log('onGetDevice', that.BTName); 
			    dev = this.getNewDevicesList(res, that.BTName)
			    this.mydevices=dev;                
			},

			bindViewTap: function(e) {
			  zksdk.stopBlueDevicesDiscovery();
			   console.log(e.currentTarget.dataset.title);
			   console.log(e.currentTarget.dataset.name);
			   var deviceId =  e.currentTarget.dataset.title;
			   var name = e.currentTarget.dataset.name;
			   wx.setStorageSync('deviceId', deviceId);
			   wx.setStorageSync('name', name);
			   wx.navigateTo({      
			     url: './cjn-print2?deviceId='+deviceId+'&name='+name + '&selIds='+this.selIds + '&prtQtys='+this.prtQtys,
			     success: function(res){
			          console.log('---bindViewTap---点击连接蓝牙--success--',res)
			     },
			     fail: function(res) {
			          console.log('---bindViewTap---点击连接蓝牙--fail--',res)
			     }
			   })
			   console.log("bindViewTap end")
			},
			
			// 正在滑动
			sliderRSSIchange: function (e) {
			  var that = this;
			  that.rssi = e.detail.value; 
			  wx.setStorageSync('RSSI', e.detail.value);    
			  console.log("sliderChange", that.rssi);
			},
		}
	}
</script>

<style>
	.section {
	  display: inline-block;
	  width: 100%;
	  position: relative;
	}
	.list-item {
	  margin-top: 20rpx;
	  margin-bottom: 20rpx; 
	  display: flex;
	  flex-direction: column;
	  box-sizing: border-box;
	  border: 1px dashed #000;
	}
	.list-item text {
	   margin-top: 10rpx;
	}
	button {
	  background: red\;
	}
	.list-item button {
	  margin-right: 10rpx;
	}
	
	page {
	  color: #333;
	}
	.devices_summary {
	  margin-top: 30px;
	  padding: 10px;
	  font-size: 16px;
	}
	.device_list {
	  height: 400px;
	  margin: 30px 5px;
	  margin-top: 0;
	  border: 1px solid #EEE;
	  border-radius: 5px;
	  width: auto;
	}
	.device_item {
	  border-bottom: 1px solid #EEE;
	  padding: 10px;
	  color: #666;
	}
	.device_item_hover {
	  background-color: rgba(0, 0, 0, .1);
	}
	.connected_info {
	  position: fixed;
	  bottom: 0;
	  width: 100%;
	  background-color: #F0F0F0;
	  padding: 10px;
	  padding-bottom: 20px;
	  margin-bottom: env(safe-area-inset-bottom);
	  font-size: 14px;
	  min-height: 100px;
	  box-shadow: 0px 0px 3px 0px;
	}
	.connected_info .operation {
	  position: absolute;
	  display: inline-block;
	  right: 30px;
	}
	.slider_bg {
	  width: 100%;
	  height: 100rpx;
	  display: flex;
	  flex-direction: row;
	  align-items: center;
	  justify-content: center;
	}
	.inputView{
	    border:  2px solid red;
	    border-radius: 40px;
	    margin-left: 15px;
	    margin-right: 15px;
	    margin-top: 15px;
	}
	.input{
	    padding-left: 10px;
	    height: 44px;
	}
</style>
